<?php

namespace App\Exceptions;

use App\Constants\ResponseArray;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    function render($request, Throwable $e)
    {
        if (DB::transactionLevel())
        {
            DB::rollBack();
        }

        if ($e instanceof AuthenticationException) {
            return response()->json(ResponseArray::unauthenticatedError(),401);
        }

        if ($e instanceof UnauthorizedHttpException) {
            return response()->json(ResponseArray::tokenExpiredError(),401);
        }

        if ($e instanceof ModelNotFoundException) {
            return response()->json(ResponseArray::notFoundError('Model'),404);
        }

        if ($e instanceof NotFoundHttpException) {
            return response()->json(ResponseArray::notFoundError());
        }

        if ($e instanceof MessageException) {

            return response()->json(ResponseArray::abortMessage($e->getMessage()));
        }

        if ($e instanceof ThrottleRequestsException) {
            return response()->json(ResponseArray::AttemptsError($e->getMessage()));
        }

        if ($request->get('debug')) {
            return parent::render($request, $e);
        }

        return response()->json(ResponseArray::renderError(get_class($e) . ':' . $e->getMessage(),$e->getTrace()));

        //return parent::render($request, $e);
    }
}
